using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.Web;
using System.ComponentModel;

namespace ThumbnailWebPart
{

    //These enums are used to specify the type for the WebPart properties. We also take advantage of the built in
    //Suppor in framework for enumeration types. SharePoint automatically generates a dropdown with all the possible values
    //for a WebPart custom property that has an enum.
    public enum ThumbnailSortBy { Display_Name, Name, Extension, Last_Modified_Date };
    public enum ThumbnailSortOrder { Ascending, Descending };
    public enum ThumbnailColumns { one = 1, two, three, four, five, six, seven, eight };
    public enum ThumbnailDirection { Horizontal, Vertical };
    public enum ThumbnailSize { _16px = 16, _32px = 32, _64px = 64, _80px = 80,_96px=96,_112px=112,_128px=128,_144px=144,_160px=160 };


    /// <summary>
    /// This WebPart is inspired in the Thumbnails Image Placerholder by Stephen Huen.
    /// For use in Microsoft Content Management Server, this is an XML placeholder control that displays 
    /// thumbnail of images in a Resource Gallery. 
    /// In authoring mode, authors specify which resource gallery to generate image thumbnails, thumbnail size, 
    /// number of thumbnails to be displayed in one table row and sorting order. 
    /// In presentation mode, all images in the Resource Gallery specified will be rendered as thumbnails with link to the full size images. 
    /// Practical application includes showing images of an event for example.Info from: http://www.codeproject.com/aspnet/thumbnailimagesph_c.asp
    /// 
    /// This WebPart provides the same functionality. It lets you indicate a SharePoint Library from where to take your images.
    /// And it let's you indicate thumbnail size, number of thumbnails per table row and sorting order.
    /// We take advantange of the fact that SharePoint Libraries generate thumbnails for the images.
    /// </summary>

    [DefaultProperty("PictureLibrary"), ToolboxData("<{0}:ThumbnailWebPart runat=server></{0}:ThumbnailWebPart>"), XmlRoot(Namespace = "ThumbnailWebPart.ThumbnailWebPart")]
    public class ThumbnailWebPart : WebPart
    {

        string _pictureLibrary = null;

        /// <summary>
        /// This property indicates the picture library that will be used for the images.
        /// </summary>
        [Browsable(false),FriendlyName("Picture Library"),Description("Holds the url that points to the list that will be used for thumnails")]
        public string PictureLibrary
        {
            get { return _pictureLibrary; }
            set { _pictureLibrary = value; }
        }
        ThumbnailSortBy _sortBy = ThumbnailSortBy.Display_Name;

        /// <summary>
        /// This property establishes with property of the image will be used when sorting them
        /// </summary>
        [Browsable(true),FriendlyName("Sort By"),Description("Establishes which criteria will be used to sort the images")]
        public ThumbnailSortBy SortBy
        {
            get { return _sortBy; }
            set { _sortBy = value; }
        }
        ThumbnailSortOrder _sortOrder = ThumbnailSortOrder.Ascending;

        /// <summary>
        /// This property establishes if the order is ascending or descending
        /// </summary>
        [Browsable(true),FriendlyName("Sort Order"),Description("Establishing if the order is ascending or descending")]
        public ThumbnailSortOrder SortOrder
        {
            get { return _sortOrder; }
            set { _sortOrder = value; }
        }
        ThumbnailColumns _columns = ThumbnailColumns.three;

        /// <summary>
        /// This property establishes how many columns will the table of images have
        /// </summary>
        [Browsable(true),FriendlyName("Columns"),Description("Indicates how many columns will the table of images have")]
        public ThumbnailColumns Columns
        {
            get { return _columns; }
            set { _columns = value; }
        }

        /*
        ThumbnailDirection _direction = ThumbnailDirection.Horizontal;

        [Browsable(true)]
        public ThumbnailDirection RepetitionDirection
        {
            get { return _direction; }
            set { _direction = value; }
        }*/

        ThumbnailSize _size = ThumbnailSize._64px;

        /// <summary>
        /// This property indicates the size the thumbnails will have
        /// </summary>
        [Browsable(true), FriendlyName("Thumbnail size"), Description("Specifies the size in pixels that the thumbnail image will have")]
        public ThumbnailSize ThumbnailSize
        {
            get { return _size; }
            set { _size = value; }
        }

        bool _showFileSize = false;

        /// <summary>
        /// If set will show the size of the image
        /// </summary>
        [Browsable(true), FriendlyName("Show File Size"), Description("If set shows the size of the file")]
        public bool ShowFileSize
        {
            get { return _showFileSize; }
            set { _showFileSize = value; }
        }


        /// <summary>
        /// Render this Web Part to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            // The EnsureChildControls method calls the
            // CreateChildControls method only if the
            // ChildControlsCreated property is false.
            EnsureChildControls();
            output.RenderBeginTag("table");
            SPContext spc = SPContext.Current;
            SPPictureLibrary library = spc.Web.Lists["nueva"] as SPPictureLibrary;
            if (library != null)
            {
                SPListItem[] item = GetSortedThumbnails(library);

                int columns = (int)Columns;
                bool first = true;
                for (int i = 0; i < item.Length; i++)
                {
                    if ((i % columns) == 0)
                    {
                        if (!first) output.RenderEndTag();
                        first = false;
                        output.RenderBeginTag("tr");
                    }
                    string itemName = item[i].Name;
                    int lastPeriod = itemName.LastIndexOf(".");
                    if (lastPeriod != -1)
                        itemName = itemName.Substring(0, lastPeriod) + "_" + itemName.Substring(lastPeriod + 1);
                    output.RenderBeginTag("td");
                    output.WriteBeginTag("img");
                    output.WriteAttribute("src", library.ParentWeb.Url + "/" + library.Title + "/_t/" + itemName + ".jpg");
                    int size = (int)_size;
                    output.WriteAttribute("height", "" + size);
                    output.WriteAttribute("width", "" + size);
                    output.WriteEndTag("img");

                    output.Write("<p align=\"center\">");
                    output.Write("<a href=\"");
                    output.Write(library.ParentWeb.Url + "/" + library.Title + "/" + item[i].Name);
                    output.Write("\">");
                    output.Write(item[i].Name);
                    output.Write("</a>");
                    if (ShowFileSize)
                    {
                        output.Write("(");
                        output.Write(item[i].File.Length);
                        output.Write(")");
                    }
                    output.Write("</p>");

                    output.RenderEndTag();
                }
            }
            output.RenderEndTag();

        }

        /// <summary>
        /// Gets all items in the list and sorts them
        /// </summary>
        /// <param name="library"></param>
        /// <returns></returns>
        private SPListItem[] GetSortedThumbnails(SPPictureLibrary library)
        {
            SPListItem[] res = new SPListItem[library.Items.Count];
            for (int i = 0; i < library.Items.Count; i++) res[i] = library.Items[i];
            Array.Sort(res, new CompareSPListItem(SortBy));
            if (SortOrder == ThumbnailSortOrder.Descending)
            {
                Array.Reverse(res);
            }
            return res;
        }


    }

    /// <summary>
    /// Implements the IComparer interface to help to sort the thumbnails
    /// </summary>
    public class CompareSPListItem : System.Collections.IComparer
    {
        ThumbnailSortBy compareBy = new ThumbnailSortBy();
        public CompareSPListItem(ThumbnailSortBy cBy)
        {
            this.compareBy = cBy;
        }

        #region IComparer Members

        public int Compare(object x, object y)
        {
            SPListItem itemX = (SPListItem)x;
            SPListItem itemY = (SPListItem)y;
            switch (compareBy)
            {
                case ThumbnailSortBy.Display_Name:
                    return String.Compare(itemX.DisplayName, itemY.DisplayName);
                case ThumbnailSortBy.Extension:
                    int indexX = itemX.Name.ToLower().LastIndexOf(".");
                    int indexY = itemY.Name.ToLower().LastIndexOf(".");

                    string extensionX = itemX.Name.Substring(indexX + 1);
                    string extensionY = itemY.Name.Substring(indexY + 1);
                    return String.Compare(extensionX, extensionY);
                case ThumbnailSortBy.Last_Modified_Date:
                    return itemX.File.TimeLastModified.CompareTo(itemY.File.TimeLastModified);
                case ThumbnailSortBy.Name:
                    return String.Compare(itemX.Name, itemY.Name);
            }
            return 0;
        }

        #endregion
    }

}
